package cn.wp.ewallet.exchange.web.controller;

import cn.hutool.db.Page;
import cn.wp.common.core.Wp;
import cn.wp.common.core.dao.SqlString;
import cn.wp.common.core.dto.WpResult;
import cn.wp.common.core.model.WpPage;
import cn.wp.common.core.web.WpUserContext;
import cn.wp.ewallet.wallet.model.entity.UserOrderDo;
import cn.wp.ewallet.wallet.model.vo.UserOrderVO;
import cn.wp.ewallet.wallet.service.UserOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import static cn.wp.ewallet.wallet.extension.constant.EwalletWalletConstant.CHECK_AMOUNT_FAILED_CODE;

@RestController
@RequestMapping(Wp.WebContext + "/ewallet/order")
@Api(tags = "A-订单")
public class UserOrderController {
    @Autowired
    private UserOrderService userOrderService;

    /**
     * 订单列表
     *
     * @param status
     * @param pageSize
     * @param pageNo
     * @param publishId
     * @param type
     * @return
     */
    @GetMapping("/get")
    @ApiOperation(value = "获取订单列表", notes = "", tags = "")
    public WpResult get(@ApiParam(name = "status", defaultValue = "0：已完成，1：待付款，2：已付款，>2：已取消") String status,
                        @ApiParam(name = "pageSize", defaultValue = "page>0") int pageSize, @ApiParam(name = "pageNo", defaultValue = "pageNo>0") int pageNo,
                        @ApiParam(name = "publishId", defaultValue = "标的（商品）ID") Integer publishId,
                        @ApiParam(name = "type", defaultValue = "0买入，1出售") Integer type) {
        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        if (type != null) {
            sb.append(" and type = '").append(type).append("'");
        }
        if (publishId != null) {
            sb.append(" and publish_id = '").append(publishId).append("'");
        }
        if (Strings.isNotBlank(status)) {
            sb.append(" and status = '").append(status).append("'");
        }
        sb.append(" and user_id = '").append(WpUserContext.get().getId()).append("'");
        sb.append(" order by create_time desc ");
        sb.append(" limit " + pageSize * (pageNo - 1) + "," + pageSize);
        return WpResult.suc(userOrderService.select(sb.toString()));
    }

    /**
     * 订单详情
     *
     * @param orderId
     * @return
     */
    @GetMapping("/detail")
    @ApiOperation(value = "订单详情", notes = "", tags = "")
    public WpResult detail(@ApiParam(required = true, name = "orderId") @RequestParam String orderId) {
        return userOrderService.getDetail(orderId);
    }


    /**
     * @param publishId   标的ID
     * @param collectType 支付方式(0微信1支付宝2银行卡)
     * @param count       数量
     * @param count       交易密码 当type为 1 出售的时候必输
     * @return
     */
    @PostMapping("/create")
    @ApiOperation(value = "创建订单", notes = "", tags = "")
    public WpResult create(String publishId,
                           String collectType,
                           BigDecimal count,
                           String transPwd) {
        return userOrderService.create(publishId, collectType, count, transPwd);
    }

    @PostMapping("/cancel")
    @ApiOperation(value = "取消订单", notes = "", tags = "")
    public WpResult upd(@ApiParam(required = true, name = "orderId") @RequestParam String orderId) {
        userOrderService.cancel(orderId, "5");
        return WpResult.suc();
    }

    @PostMapping("/pay")
    @ApiOperation(value = "支付", notes = "", tags = "")
    public WpResult pay(@ApiParam(required = true, name = "orderId") @RequestParam String orderId) {
        userOrderService.pay(orderId);
        return WpResult.suc();
    }

    @PostMapping("/finish")
    @ApiOperation(value = "完成", notes = "", tags = "")
    public WpResult finish(@ApiParam(required = true, name = "orderId") @RequestParam String orderId) {
        userOrderService.finish(orderId);
        return WpResult.suc();
    }

    @GetMapping("countToday")
    @ApiOperation("今日交易额统计")
    public WpResult countToday(){
        long zero = System.currentTimeMillis() / (1000 * 3600 * 24) * (1000 * 3600 * 24);
        WpResult suc = WpResult.suc(userOrderService
                .select("status = 0 and second_time between " + (zero - TimeZone.getDefault().getRawOffset()) + " and " + (zero + 24 * 60 * 60 * 1000))
                .stream()
                .mapToDouble(userOrderDo -> userOrderDo.getCount().doubleValue())
                .sum()
        );
        return suc;
    }

    @GetMapping("/sysQuery")
    public WpResult sysQuery(WpPage wpPage, String status, String orderId) {
        WpPage<UserOrderVO> userOrderDoWpPage = userOrderService.selectList("select o.*,u.user_tel as phone,user_nikename as nickName from user_order o left join pa_user_info u on u.user_id = o.user_id", new Object[]{}, wpPage, UserOrderVO.class);
        return WpResult.suc(userOrderDoWpPage);
    }

    @PostMapping("/revert")
    @ApiOperation(value = "取消订单", notes = "", tags = "")
    public WpResult sysCancel
            (@ApiParam(required = true, name = "orderId") @RequestParam String orderId) {
        userOrderService.cancel(orderId, "6");
        return WpResult.suc();
    }

}
